﻿using Manager.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using System.Windows.Forms;
using UboxUI;

namespace Manager
{
    public partial class FrmManagerCreate : FrmFather
    {
        public FrmManagerCreate()
        {
            InitializeComponent();
            #region 視窗初始化

            this.LblTitle.Text = this.Text;
            this.LblTitle2.Text = LblTitle.Text;
            this.BtnClose.Left = this.Width - this.BtnClose.Width - 10;
            this.BtnNarrow.Left = this.BtnClose.Left - this.BtnNarrow.Width - 10;
            this.panel1.Top = 0;
            this.panel2.Top = this.panel1.Height;

            #endregion
        }

        private void FrmManagerCreate_Load(object sender, EventArgs e)
        {
            #region 元件初始化

            CboLevel.SelectedIndex = 2;
            CboLevel.DropDownStyle = ComboBoxStyle.DropDownList;
            TxtPassword.UseSystemPasswordChar = !TxtPassword.UseSystemPasswordChar;
            openFileDialog1.FileName = "";
            openFileDialog1.Filter = "(*.bmp)|*.bmp|(*.jpg)|*.jpg|(*.png)|*.png|(*.gif)|*.gif";

            #endregion
        }

        private void BtnOpenimage_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                PicImage.ImageLocation = openFileDialog1.FileName;
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BtnInsert_Click(object sender, EventArgs e)
        {
            int check = 0;
            try
            {
                #region SQL 檢查帳號是否存在
                string strsql = @"
                             if exists(
                                select manager_username 
                                from manager
                                where manager_username=@Username
                               )
                               begin
                               set @Usernum =1
                               end
                              else
                                  begin
                                 set @Usernum =0
                                  end
                             ";

                #endregion

                #region SQL 創建帳號
                string strsql2 = @"
                              Insert Into Manager(
                                                  manager_Username,
                                                  manager_Password,
                                                  manager_first_name,
                                                  manager_last_name,
                                                  manager_level,
                                                  manager_password_random,
                                                  manager_registration_date,
                                                  manager_image
                                                 ) 
                             Values(
                                    @Username,
                                    @Password,
                                    @Firstname,
                                    @Lastname,
                                    @Level,
                                    @Randomnum,
                                    @Registration_date,
                                    @Image
                                    )
	                         select @Id =SCOPE_IDENTITY()
                             ";
                #endregion

                #region 連線設定

                string strconn = Settings.Default.strConn.ToString();
                SqlConnection conn = new SqlConnection(strconn);

                #endregion

                #region step1檢查輸入

                if (TxtUsername.TextLength < 10)
                {
                    check = 1;
                    throw new Exception("帳號請輸入10字元以上");
                }
                else if (TxtPassword.TextLength < 10)
                {
                    check = 1;
                    throw new Exception("密碼請輸入10字元以上");
                }

                #endregion

                #region step2檢查帳號是否存在
                try
                {
                    #region cme設定
                    SqlCommand cmd = new SqlCommand(strsql, conn);
                    cmd.CommandType = CommandType.Text;
                    #endregion

                    #region Input變數
                    SqlParameter Username = new SqlParameter("@Username", SqlDbType.NVarChar, 20);
                    Username.Direction = ParameterDirection.Input;
                    Username.Value = this.TxtUsername.Text;
                    cmd.Parameters.Add(Username);
                    #endregion

                    #region Output變數
                    SqlParameter usernum = new SqlParameter("@Usernum", SqlDbType.Int, 1);
                    usernum.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(usernum);
                    #endregion

                    #region 執行
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    check = Convert.ToInt16(cmd.Parameters["@Usernum"].Value);
                    cmd.Dispose();
                    conn.Close();

                    #endregion
                }
                catch
                {
                    throw new Exception("新增失敗");
                }


                #endregion

                #region step3創建帳號

                if (check == 1)
                {
                    throw new Exception("帳號重複");
                }
                else
                {

                    #region cme設定
                    SqlCommand cmd = new SqlCommand(strsql2, conn);
                    cmd.CommandType = CommandType.Text;
                    #endregion

                    #region Input變數
                    SqlParameter num = new SqlParameter("@Randomnum", SqlDbType.Int);
                    num.Direction = ParameterDirection.Input;
                    Random i = new Random(Guid.NewGuid().GetHashCode());
                    num.Value = i.Next(0, 9999999);
                    cmd.Parameters.Add(num);

                    SqlParameter Username = new SqlParameter("@Username", SqlDbType.NVarChar, 20);
                    Username.Direction = ParameterDirection.Input;
                    Username.Value = this.TxtUsername.Text;
                    cmd.Parameters.Add(Username);

                    SqlParameter Password = new SqlParameter("@Password", SqlDbType.NVarChar, 20);
                    Password.Direction = ParameterDirection.Input;
                    Password.Value = FormsAuthentication.HashPasswordForStoringInConfigFile(this.TxtPassword.Text + num.Value.ToString(), "sha1");
                    cmd.Parameters.Add(Password);

                    SqlParameter Firstname = new SqlParameter("@Firstname", SqlDbType.NVarChar, 10);
                    Firstname.Direction = ParameterDirection.Input;
                    Firstname.Value = this.TxtFirstname.Text;
                    cmd.Parameters.Add(Firstname);

                    SqlParameter Lastname = new SqlParameter("@Lastname", SqlDbType.NVarChar, 10);
                    Lastname.Direction = ParameterDirection.Input;
                    Lastname.Value = this.TxtLastname.Text;
                    cmd.Parameters.Add(Lastname);

                    SqlParameter Level = new SqlParameter("@Level", SqlDbType.Char, 1);
                    Level.Direction = ParameterDirection.Input;
                    Level.Value = CboLevel.SelectedIndex;
                    cmd.Parameters.Add(Level);

                    SqlParameter Registration_date = new SqlParameter("@Registration_date", SqlDbType.DateTime, 20);
                    Registration_date.Direction = ParameterDirection.Input;
                    Registration_date.Value = DateTime.Now;
                    cmd.Parameters.Add(Registration_date);
                    try
                    {
                        MemoryStream st = new MemoryStream();
                        PicImage.Image.Save(st, PicImage.Image.RawFormat);
                        byte[] by = st.ToArray();
                        SqlParameter Image = new SqlParameter("@Image", SqlDbType.VarBinary);
                        Image.Direction = ParameterDirection.Input;
                        Image.Value = by;
                        cmd.Parameters.Add(Image);
                    }
                    catch
                    {
                        throw new Exception("未選圖"); 
                    }
                    #endregion

                    #region Output變數
                    SqlParameter Id = new SqlParameter("@Id", SqlDbType.Int, 2);
                    Id.Direction = ParameterDirection.Output;
                    cmd.Parameters.Add(Id);
                    #endregion

                    #region 執行
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    int n = Convert.ToInt16(cmd.Parameters["@Id"].Value);
                    cmd.Dispose();
                    conn.Close();
                    conn.Dispose();
                    if (n > 0) { throw new Exception("新增成功"); }
                    #endregion

                    conn.Dispose();
                }
                #endregion
            }
            catch (Exception ex)
            {
                LblMessage.Text= ex.Message;
            }
        }

        private void TxtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("帳號不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                LblMessage.Text = ex.Message;
            }
        }

        private void TxtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("密碼不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                LblMessage.Text = ex.Message;
            }
        }



        #region 按鈕的樣式

        private void BtnInsert_MouseEnter(object sender, EventArgs e)
        {
            this.BtnInsert.FlatAppearance.BorderSize = 0;
            this.BtnInsert.ForeColor = Color.White;
        }

        private void BtnInsert_MouseLeave(object sender, EventArgs e)
        {
            this.BtnInsert.FlatAppearance.BorderSize = 1;
            this.BtnInsert.ForeColor = Color.Black;
        }

        private void BtnCancel_MouseEnter(object sender, EventArgs e)
        {
            this.BtnCancel.FlatAppearance.BorderSize = 0;
            this.BtnCancel.ForeColor = Color.White;
        }

        private void BtnCancel_MouseLeave(object sender, EventArgs e)
        {
            this.BtnCancel.FlatAppearance.BorderSize = 1;
            this.BtnCancel.ForeColor = Color.Black;
        }
         #endregion
    }
}
